#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
数据库初始化脚本
用于确保Docker容器中的数据库正确初始化并支持UTF-8编码
"""

import sqlite3
import os
import sys

# 数据库配置
DATABASE = 'filemanager.db'

def init_database():
    """初始化数据库，确保UTF-8编码支持"""
    try:
        print(f"正在初始化数据库: {DATABASE}")
        
        # 连接数据库
        conn = sqlite3.connect(DATABASE)
        
        # 设置UTF-8编码支持
        conn.execute('PRAGMA encoding = "UTF-8"')
        conn.execute('PRAGMA journal_mode = WAL')
        conn.execute('PRAGMA synchronous = NORMAL')
        
        cursor = conn.cursor()
        
        # 创建files表
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS files (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                filename TEXT NOT NULL,
                original_filename TEXT,
                filepath TEXT NOT NULL,
                filesize INTEGER,
                upload_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                file_type TEXT,
                folder TEXT
            )
        ''')
        
        # 检查是否需要添加新字段（向后兼容）
        cursor.execute("PRAGMA table_info(files)")
        columns = [column[1] for column in cursor.fetchall()]
        
        if 'original_filename' not in columns:
            print("添加 original_filename 字段...")
            cursor.execute('ALTER TABLE files ADD COLUMN original_filename TEXT')
        
        if 'folder' not in columns:
            print("添加 folder 字段...")
            cursor.execute('ALTER TABLE files ADD COLUMN folder TEXT')
        
        # 提交更改
        conn.commit()
        
        # 验证数据库编码
        cursor.execute('PRAGMA encoding')
        encoding = cursor.fetchone()[0]
        print(f"数据库编码: {encoding}")
        
        # 测试中文支持
        cursor.execute("SELECT '测试中文字符' as test_chinese")
        result = cursor.fetchone()[0]
        print(f"中文测试结果: {result}")
        
        conn.close()
        print("数据库初始化完成！")
        return True
        
    except Exception as e:
        print(f"数据库初始化失败: {str(e)}")
        return False

if __name__ == '__main__':
    success = init_database()
    sys.exit(0 if success else 1)